package com.fjb.tool.zookeeper.lock;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.data.Stat;

public class TaskDemo implements Runnable{

	private int loop;
    private Long lockid;
    ZookerSession zs;
    public TaskDemo(int loop,Long lockid) {
        zs = ZookerSession.getInstance();
        this.loop = loop;
        this.lockid = lockid;
    }
 
    @Override
    public void run() {
        ZookerSession.getInstance().acquireDistributeLock(lockid);
        for(int i=0;i<loop;i++){
            int count = getcount();
            System.out.println(Thread.currentThread().getName()+"-->"+count);
            count(++count);
        }
        zs.releaseDistributeLock(lockid);
    }
    //计数
    public void count(int count){
        try {
            Stat s = zs.getZooKeeper().exists("/count", false);
            if(s==null){
                System.out.println("count 不存在");
                zs.getZooKeeper().create("/count",String.valueOf(count).getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
            }else{
                zs.getZooKeeper().setData("/count",String.valueOf(count).getBytes(),-1);
            }
        } catch (KeeperException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    public int getcount(){
        try {
            Stat s = zs.getZooKeeper().exists("/count", false);
            if(s==null){
                zs.getZooKeeper().create("/count",String.valueOf(0).getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
                return 0;
            }else{
                byte[] data = zs.getZooKeeper().getData("/count", false, null);
                return Integer.valueOf(new String(data));
            }
        } catch (KeeperException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return -1;
    }
    
    public static void main(String[] args) {
        long LOCKID = 2l;
        for(int i=0;i<100;i++){
            new Thread(new TaskDemo(1, LOCKID)).start();
        }
    }
}
